import {usePermissionStore} from "@/store/permission.store.js";
import {createRouter, createWebHistory} from "vue-router";
import routes from "@/router/routes.js";
import {ElLoading, ElMessage} from "element-plus";
import {useAccountStore} from "@/store/account.store.js";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: routes,
});
let isInitialized = false;
let isFirst = true;
let isLoadingInstance = null;
// 白名单：无需登录即可访问的路由 name 或 path
const WHITE_LIST = [
    'login',
    'error',
    'NotFound',
];
router.beforeEach(async (to, from, next) => {
    // 鉴权后的初始化
    const permissionStore = usePermissionStore();
    const accountStore = useAccountStore();
    let isAuthorized = await accountStore.authenticated()
    if (to.name === "login") {
        isAuthorized = false; // 登录页面不需要鉴权
    }
    if (isAuthorized) {
        if (!isInitialized) {
            await permissionStore.initialRoutes();
            isInitialized = true;
            return next({path: permissionStore?.activeRoute || "/"});
        } else {
            next();
        }
    } else {
        if (to.name !== "login") {
            if (!isInitialized) {
                ElMessage.error("拒绝访问！请先进行系统登陆");
            }
            return next({name: "login"});
        } else {
            next();
        }
    }
});

router.afterEach((to, from, failure) => {

    if (failure && to.path !== from.path) {
        ElMessage.error("路由跳转异常")
    } else {
        // 更新页面标题
        document.title = to.meta.title || import.meta.env.VITE_APP_TITLE || "Vue App";
    }
    // if (isLoadingInstance) {
    //     isLoadingInstance.close();
    //     isLoadingInstance = null;
    // }
});

export default router;
